package com.amkai.aes.webservice.binary.objecthandler.inventory;

import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.inventory.hql.AesCriteria;
import com.amkai.aes.aescommon.service.binary.job.inventory.hql.AesCriteriaJob;
import com.amkai.aes.aescommon.service.binary.job.inventory.hql.AesCriteriaResult;
import com.amkai.aes.aescommon.service.binary.job.inventory.hql.AesParameterValue;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.rad.designerbase.beans.RADBean;

public class AesCriteriaJobHandler<Type> implements JobObjectHandler<AesCriteriaJob<Type>, AesCriteria, AesCriteriaResult<Type>> {
	private static final Log logger = LogFactory.getLog(AesCriteriaJobHandler.class);

	@Override
	public AesCriteriaResult<Type> process(AesCriteriaJob<Type> job, AesCriteria criteria)
			throws Exception {
		AesCriteriaResult<Type> result = new AesCriteriaResult<Type>();
		if (criteria == null) return result;

		SessionManager sm = null;
		try {
			sm = SiteManager.Start();
			sm.openSession();
			sm.openTransaction();
			Query query = sm.execute(criteria.toHqlString());
			for (AesParameterValue value : criteria.getValues()) {
				if (value.getValue() instanceof Collection<?>) {
					query.setParameterList(value.getName(), (Collection<?>)value.getValue());
				} else {
					query.setParameter(value.getName(), value.getValue());
				}
			}
			List<?> queryResult = query.list();
			for (Object obj : queryResult) {
				if (!(obj instanceof RADBean)) continue;
				criteria.resolveProperties((RADBean)obj);
			}
			result.setResultList(queryResult);
			sm.commitTransaction();
			return result;
			
		} catch (Exception e) {
			logger.error(criteria.toHqlString(), e);
			if (sm != null) {
				sm.rollbackTransaction();
			}
			throw e;
		} finally {
			if (sm != null) {
				sm.closeSession();
			}
		}
	}

}
